package com.ruoyi.project.lely.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.project.lely.bean.entity.LyCart;
import com.ruoyi.project.lely.bean.vo.LyCartItemsVO;
import com.ruoyi.common.R;
import com.ruoyi.common.SecurityUtils;
import com.ruoyi.project.lely.constant.CommonConstant;
import com.ruoyi.project.lely.mapper.LyCartMapper;
import com.ruoyi.project.lely.service.LyCartService;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.stereotype.Service;

/**
 * @Desc: 购物车
 * @Author LuoYong
 * @Date 2022/1/17 18:14
 */
@DataSource(value = DataSourceType.SLAVE)
@Service
public class LyCartServiceImpl extends ServiceImpl<LyCartMapper, LyCart> implements LyCartService {

    /**
     * 购物车详情
     *
     * @return
     */
    @Override
    public R get() {
        LyCartItemsVO vo = new LyCartItemsVO();
        List<LyCart> list = this.list(
                new LambdaQueryWrapper<LyCart>()
                        .eq(LyCart::getUserId, SecurityUtils.getUserId())
                        .eq(LyCart::getDeleted, CommonConstant.DELETED)
        );

        if (CollUtil.isNotEmpty(list)) {
            AtomicReference<BigDecimal> goodsAmount = new AtomicReference<>(new BigDecimal(0.00));
            AtomicReference<Integer> goodsCount = new AtomicReference<>(new Integer(0));
            list.stream().forEach(cart -> {
                goodsAmount.get().add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
                goodsCount.getAndSet(goodsCount.get() + 1);
            });
            // 菜品总价格
            vo.setGoodsAmount(goodsAmount.get());
            vo.setGoodsCount(goodsCount.get());
            vo.setCartList(list);
        }
        return R.ok(vo);
    }
}
